#include "chooselevelwindow.h"
#include "ui_chooselevelwindow.h"

#include <QPainter>
#include <QTimer>
#include <QLabel>
#include <QStyle>
#include <QFileDialog>
#include <QDebug>
#include "imgbutton.h"

ChooseLevelWindow::ChooseLevelWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ChooseLevelWindow)
{
    ui->setupUi(this);

    ui->btnReturn->setAnimationImgPath(":/res/backBtn_1.png", ":/res/backBtn_2.png");
    ui->btnReadMap->setAnimationImgPath(":/res/loadBtn_1.png", ":/res/loadBtn_2.png");

    //关卡选择按钮生成
    for (int i = 0; i < 16; i++) {
        QPushButton *tmpBtn = new QPushButton(this);
        tmpBtn->setText(QString::number(i+1));
        tmpBtn->setFixedSize(60, 60);
        tmpBtn->setObjectName("img_button");
        tmpBtn->setStyleSheet("#img_button{border-image:url(:/res/chooseBtn_1.png); color:rgb(20,20,20); font-size:20px;}"
                              "#img_button:pressed{border-image: url(:/res/chooseBtn_2.png);}");
        tmpBtn->move(145+(i%4)*150, 90+(i/4)*100);
        tmpBtn->show();

        //绑定按钮点击事件
        connect(tmpBtn, &ImgButton::clicked, [=](){
            QTimer::singleShot(100, [=](){
                this->hide();
                playWindow = new PlayWindow(QString(":/mazedata/").append(QString::number(i+1)).append(".mazedata"));
                playWindow->setGeometry(this->geometry());
                playWindow->show();

                //监听游戏窗口的返回按钮点击事件
                connect(playWindow, &PlayWindow::backBtnClicked, [=](){
                   playWindow->hide();
                   setGeometry(playWindow->geometry());
                   delete playWindow;
                   playWindow = NULL;
                   this->show();
                });
            });
        });
    }
}

ChooseLevelWindow::~ChooseLevelWindow()
{
    delete ui;
}

//void ChooseLevelWindow::paintEvent(QPaintEvent *e)
//{
//    QPainter painter(this);
//    QPixmap pix;
//    pix.load(":/res/background2.jpg");
//    painter.drawPixmap(0,0,pix);
//}

void ChooseLevelWindow::on_btnReadMap_clicked()
{
    QTimer::singleShot(100, [=](){
        QString path = QFileDialog::getOpenFileName(this,
                                                    "读取迷宫地图","./","(*.mazedata)");
        //返回值不为空说明成功选取迷宫文件
        if (path!=NULL) {
            this->hide();
            playWindow = new PlayWindow(path);
            playWindow->setGeometry(this->geometry());
            playWindow->show();

            //监听游戏窗口的返回按钮点击事件
            connect(playWindow, &PlayWindow::backBtnClicked, [=](){
                playWindow->hide();
                setGeometry(playWindow->geometry());
                delete playWindow;
                playWindow = NULL;
                this->show();
            });
        }
    });
}

void ChooseLevelWindow::on_btnReturn_clicked()
{
    QTimer::singleShot(100, [=](){
        emit(backBtnClicked());
    });
}

